package com.powernode.handler;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.constant.AuthConstants;
import com.powernode.constant.BusinessEnum;
import com.powernode.model.LoginUserDetails;
import com.powernode.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.Duration;
import java.util.HashMap;

/**
 * @description:
 * @author: mky
 * @date: 2024/7/5 11:33
 * @version: 1.0
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //登录成功，返回token，然后存入redis
        LoginUserDetails principal = (LoginUserDetails) authentication.getPrincipal();
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(principal);
//        String jsonString = JSON.toJSONString(principal);
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,jsonString,Duration.ofSeconds(AuthConstants.TOKEN_EXPIRES_SECOND));
        response.setContentType(AuthConstants.APPLICATION_JSON);
        response.setCharacterEncoding(AuthConstants.UTF_8);
        HashMap<String, String> resultMap = new HashMap<>();
        resultMap.put("token",AuthConstants.TOKEN_PREFIX+token);
        resultMap.put("TokenExpiresSecond",AuthConstants.TOKEN_EXPIRES_SECOND.toString());
        Result<Object> result = new Result<>();
        result.setCode(BusinessEnum.SUCCESS.getCode());
        result.setMsg(BusinessEnum.SUCCESS.getMsg());
        result.setData(resultMap);
//        ObjectMapper objectMapper = new ObjectMapper();
        String resultStr = objectMapper.writeValueAsString(result);
        PrintWriter writer = response.getWriter();
        writer.write(resultStr);
        writer.flush();
        writer.close();
    }
}
